﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace VisionCloud.Utility
{
    public static class IocHelper
    {
        public static void RegisterModel(this ContainerBuilder builder, string assemblyString, Func<Type, bool> whereFunc)
        {
            var assemblies1 = Assembly.Load(assemblyString).GetTypes()
                .Where(whereFunc);
            foreach (var ass in assemblies1)
            {
                builder.RegisterType(ass).EnableClassInterceptors()
                    .PropertiesAutowired()
                    .InstancePerLifetimeScope();
            }
        }

        public static void RegisterModelWithInterface(this ContainerBuilder builder, string assemblyString, Func<Type, bool> whereFunc)
        {
            var assemblies1 = Assembly.Load(assemblyString).GetTypes()
                .Where(whereFunc);
            foreach (var ass in assemblies1)
            {
                builder.RegisterType(ass).As(ass.GetInterfaces())
                    .PropertiesAutowired()
                    .InstancePerLifetimeScope();
            }
        }

        public static void RegisterController(this ContainerBuilder builder, string assemblyString)
        {
            var assemblies1 = Assembly.Load(assemblyString).GetExportedTypes()
                .Where(type => typeof(ControllerBase).IsAssignableFrom(type));
            builder.RegisterTypes(assemblies1.ToArray())
                .PropertiesAutowired();
        }

        public static async Task GetResolveObj<T>(Action<T> action)
        {
            using (var container = StartupServer.IocContainer.BeginLifetimeScope())
            {
                action(container.Resolve<T>());
            }
        }
    }
}